var FManager = {
	init: function(){},
	sanitizeLabel: function(name){
		return name.toLowerCase();
	},
	serialize: function(value, key){
		// nie interpretuje wogule array ..?? ale dziala
		if (null === value){
			return '&';
		} else
		if (true === value) {
			return '1&';
		} else
		if (false === value) {
			return '0&';
		} else
		if (typeof value === 'object') {
			var url = [];
			$.each(value, function(i,e){
				var k = key === undefined ? i :  key+'['+i+']';
				if (typeof e === 'object') {
					url.push(FManager.serialize(e, k));
				} else {
					url.push(k+'=' + FManager.serialize(e, k));
				}
			});
			return url.join('&');
		} else {
			return value.toString();
		}
	},
	generateElementId: function(){
		if (undefined === this.element) {
			this.element = 0;
		}
		return this.element++;
	},
	generateLabelId: function(){
		if (undefined === this.label) {
			this.label = 0;
		}
		return this.label++;
	},
	// PParsowanie ustawień
	prepareSettingsForElement: function(options){
		// brak konfiguracji jest ustawiana
		if (typeof options !== 'object') {
			options = {
				required: -1,
				strlen_min: -1,
				strlen_max: -1,
				email: -1,
				elements: ''
			};
		}
		
		// ustawianie konfiguracji
		// required
		options.required == (options['required'] == undefined) ? -1 : 1
		if(options['validators'] !== undefined) {
			if (options['validators']['strlen'] !== undefined) {
				// strlen_min
				options.strlen_min == (options['validators']['strlen']['options']['min'] == undefined) ? -1 : options['validators']['strlen']['options']['min'];
				// strlen_max
				options.strlen_max == (options['validators']['strlen']['options']['max'] == undefined) ? -1 : options['validators']['strlen']['options']['max'];
			}
			
			if (options['validators']['email'] !== undefined) {
				// email
				options.email == (options['validators']['email'] == undefined) ? -1 : 1;
			}
		}

		return options;
	},
	getSettingsForElement: function(id, type){		
		var options = FManager.getSettingsOptForElement(id);
		if (typeof options !== 'object') {
			return {};
		}

		var returnOptions = {
			required: false,
			validators: {}	
		}

		if (options.required != -1) {
			returnOptions['required'] = true
		}
		
		if (options.strlen_min > -1) {
			returnOptions['validators'] = {
				strlen: {
					validator: 'StringLength',
					options: { min: options.strlen_min }
				}
			};
		}

		if (options.strlen_max > -1) {
			if (returnOptions['validators']['strlen'] === undefined) {
				returnOptions['validators'] = {
					strlen: {
						validator: 'StringLength',
						options: {}
					}
				};
			}

			returnOptions['validators']['strlen']['options']['max'] = options.strlen_max
		}
		
		if (options.email != -1) {
			$.extend(returnOptions['validators'], {
				email: {
					validator: 'EmailAddress'
				}
			});
		}

		if (options.elements != -1) {
			var val = '';
			var array = options.elements.split(',');
			var opt = {}
			for(i = 0; i< array.length; i++){
				val = $.trim(array[i]);
				opt[val] = val;
			}
			switch(type){
				case 'select':
					$.extend(returnOptions, { multiOptions: opt });
					break;
				case 'MultiCheckbox':
					$.extend(returnOptions, { multiOptions: opt });
					break;
			}
		}
		
		return returnOptions;
	},
	// Przechowywanie info jaki element jakie opcje ma zaznaczone
	_settingsEl: new Array(),
	setSettingsOptForElement: function(id, settings){
		FManager._settingsEl[id] = settings;
	},
	getSettingsOptForElement: function(id){
		return FManager._settingsEl[id];
	},
	getElemetnType : function(type){
		switch(type){
			case '': 
			case 'input-text': return 'text';
			case 'input-textarea': return 'textarea';
			case 'input-radio': return 'radio';
			case 'input-checkbox': return 'checkbox';
			case 'input-multicheckbox': return 'MultiCheckbox';
			case 'input-submit': return 'submit';
			case 'input-reset': return 'reset';
			case 'input-select': return 'select'
		}
		return false;
	},
	getElemetnNameByType : function(name){
		switch(name){
			case '': 
			case 'text': return 'input-text';
			case 'textarea': return 'input-textarea';
			case 'radio': return 'input-radio';
			case 'checkbox': return 'input-checkbox';
			case 'MultiCheckbox': return 'input-multicheckbox';
			case 'submit': return 'input-submit';
			case 'reset': return 'input-reset';
			case 'select': return 'input-select'
		}
		return false;
	},
	setFormsArray: function(json){
		var formContent = $('#forms-content');
		// czyszczenie wszystkich elementow ..
		formContent.find('.form-element-wraper').remove();

		$.each(json.elements, function(k,i){
			// pobieranie podstawowych opcji
			var labelName = i.options.label;
			var labelSanitized = k;
			var id = FManager.generateElementId();
			var type = i.type
			var name = FManager.getElemetnNameByType(type);
			var options = FManager.prepareSettingsForElement(i.options);

			// ustawianie opcji
			FManager.setSettingsOptForElement(id, options);
			
			// tworzenie elementu

			// ?? czy ten komentarz napewno
			// dziwne zachowanie przy sortowaniu, dlatego usuniecie
			// class `form-element`
			var cloneElement = $('#' + name).clone();
			cloneElement
				.attr('fid', id)
				.removeClass('form-element')
				.addClass('form-element-use');
			
			// tworzenie wrappera
			var wraper = $('#forms-base .form-element-wraper').clone();
			wraper.show();
			var label = wraper.find('input[name=label]');
			label.val(labelName);

			// dodanie wrapera do listy
			formContent.append(wraper);
			formContent.sortable('refresh');
			
			// laczenie wrappera z elementem
			$(wraper).find('.form-element-handler').append(cloneElement);
			$('.form-element-handler').sortable('refresh');
		});
	},
	getFormsArray: function(){
		var forms = {
			action: null,
			method: 'post',
			elements: {}
		};

		$('#forms-content .form-element-wraper').map(function(){
			var wraper = $(this);

			var label = wraper.find('input[name=label]').val();
			labelSanitized = FManager.sanitizeLabel(label);

			var element = wraper.find('.form-element-use');
			var id = element.attr('fid');
			var type = FManager.getElemetnType(element.attr('id'));
			var options = FManager.setSettingsOptForElement(id, type);

			if (typeof options !== 'object') {
				options = {};
			}

			options['label'] = label;

			forms.elements[labelSanitized] = {
				type: type,
				options: options
			};
		});

		return forms;
	}
};	